﻿using System.Xml.Linq;

namespace TPXSDK.NET.Share;

/// <summary>
/// 访问系统资源获得翻译字符串
/// </summary>
public static class Tr
{
    private static readonly Dictionary<string, string> _dict = [];

    /// <summary>
    /// 根据语言文件初始化
    /// </summary>
    /// <param name="fn"></param>
    public static bool Init(string fn)
    {
        _dict.Clear();
        // 加载，FIXM
        if (!File.Exists(fn))
        {
            return false;
        }
        // 加载 XML 文件
        var xmlDoc = XDocument.Load(fn);

        // 查询根节点下的所有子节点
        var elements = xmlDoc.Root?.Elements();
        if (null == elements)
        {
            return false;
        }

        foreach (var element in elements)
        {
            //Trace.WriteLine("Node Name: " + element.Name);
            //Trace.WriteLine("Node Value: " + element.Value);
            if (element.Name != "Item")
            {
                continue;
            }
            // 读取属性
            var keyAttr = element.Attribute("Key");
            var valAttr = element.Attribute("Val");
            if (null != keyAttr && null != valAttr)
            {
                _dict.Add(keyAttr.Value, valAttr.Value);
            }            
        }
        return true;
    }

    /// <summary>
    /// 根据键值获得翻译字符串
    /// </summary>
    public static string Get(string key)
    {
        return _dict.TryGetValue(key, out var ret) ? ret : $"{key}?";
    }
}
